import ServiceExtensionAbility from '@ohos.application.ServiceExtensionAbility'
import display from '@ohos.display';
import window from '@ohos.window';
import ConfigData from '../../../../../../../common/utils/src/main/ets/default/baseUtil/ConfigData';
import LogUtil from '../../../../../../../common/utils/src/main/ets/default/baseUtil/LogUtil';
import { StyleConstants } from '../common/constants/StyleConstants'
import commonEvent from '@ohos.commonEvent';
import Window from '@ohos.window';
import inputMonitor from '@ohos.multimodalInput.inputMonitor';

const TAG = 'ServiceExtension'

export default class ServiceExtension extends ServiceExtensionAbility {
    async onCreate(want) {
        LogUtil.info(TAG + ' onCreate, want: ' + JSON.stringify(want.abilityName))

        globalThis.context = this.context

        globalThis.screenWidth = (await this.getWindowDisplayData()).width
        globalThis.screenHeight = (await this.getWindowDisplayData()).height
        LogUtil.info(ConfigData.TAG + 'screenWidth: ' + globalThis.screenWidth + ' screenHeight: ' + globalThis.screenHeight);

        this.ceListener()

        this.initWindow()

        // 全局键值监听
        inputMonitor.on("keyboard", (t)=>{
            LogUtil.info(TAG + `onCreate, inputMonitor.on t: ${JSON.stringify(t)}`);

            let code = t.keyCode
            let keyType = t.type
            switch (code) {
                case 2:
                    LogUtil.info(TAG + " case 2");

                    if (keyType == 1&& globalThis.destroyFlag) {
                        LogUtil.info(TAG + " case 2, keyType = 1");
                        globalThis.context.terminateSelf().then((data) => {
                            // 执行正常业务
                            LogUtil.info('terminateSelf succeed');
                        }).catch((error) => {
                            // 处理业务逻辑错误
                            LogUtil.info('terminateSelf failed, error.code: ' + JSON.stringify(error.code) +
                            ' error.message: ' + JSON.stringify(error.message));
                        });
                    }

                    break;
            }
        })
    }
    onRequest(want, startId) {
        LogUtil.info(TAG + ' onRequest, want: ' + JSON.stringify(want.abilityName))
    }
    onConnect(want) {
        LogUtil.info(TAG + ' onConnect, want: ' + JSON.stringify(want.abilityName))
        return null;
    }
    onDisconnect(want) {
        LogUtil.info(TAG + ' onDisconnect, want: ' + JSON.stringify(want.abilityName))
    }
    onDestroy() {
        LogUtil.info(TAG + ' onDestroy')

        this.destroyWindow(StyleConstants.WINDOW_NAME);
    }

    private destroyWindow(name: string): void {
        LogUtil.info(TAG + `destroyWindow, name ${name}`);
        this.findWindow(name, (win) => {
            LogUtil.info(TAG + `hideWindow, findWindow callback name: ${name}`);
            win.destroy().then(() => {
                LogUtil.info(TAG + `destroyWindow, destroy then name: ${name}`);
            });
        });
    }

    private findWindow(name: string, callback?: Function): void {
        LogUtil.info(TAG + `findWindow, name ${name}`);
        void Window.find(name)
            .then((win) => {
                LogUtil.info(TAG + `findWindow, find then name: ${name}`);
                if (callback) {
                    callback(win);
                }
            });
    }

    private ceListener() {
        // 接收Settings的通知，当Settings在前台时，销毁Settings_Menu
        commonEvent.createSubscriber({events: ["SETTINGS_FOREGROUND"]})
            .then((commonEventSubscriber) => {
                LogUtil.info(TAG + ' createSubscriber, commonEventSubscriber: ' + JSON.stringify(commonEventSubscriber))
                commonEvent.subscribe(commonEventSubscriber, (err, data) => {
                    LogUtil.info(TAG + ' subscribe, data: ' + JSON.stringify(data))
                    if(err.code !== 0){
                        console.log("=-= subscribe err, err: " +JSON.stringify(err));
                        return;
                    }

//                    globalThis.context.terminateSelf().then((data) => {
//                        // 执行正常业务
//                        console.log('terminateSelf succeed');
//                    }).catch((error) => {
//                        // 处理业务逻辑错误
//                        console.log('terminateSelf failed, error.code: ' + JSON.stringify(error.code) +
//                        ' error.message: ' + JSON.stringify(error.message));
//                    });
                })
            })
            .catch((err) => {
                console.log("=-= createSubscriber fail, err: "+ JSON.stringify(err));
            })
    }

    private async getWindowDisplayData() {
        let displayData: display.Display = null;
        await display.getDefaultDisplay()
            .then((res)=>{
                displayData = res;
            }).catch((err)=>{
                LogUtil.error(ConfigData.TAG + 'getWindowDisplayData error:' + err);
            });
        return displayData;
    }

    private initWindow(): void {
        window.create(this.context, StyleConstants.WINDOW_NAME, 2106).then((win) => {
            win.resetSize(globalThis.screenWidth * 0.4, globalThis.screenHeight * 0.7).then(() => {
                win.moveTo(globalThis.screenWidth * 0.05, globalThis.screenHeight * 0.05).then(() => {
                    win.loadContent('pages/index').then(() => {
                        win.show().then(()=>{

                        })
                    })
                })
            })
        })
    }
}